package com.github.caiqy.shirodemo.web;

import com.github.caiqy.shirodemo.web.vo.LoginRequest;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ShiroTestController {

    @PostMapping("/login")
    public Object login(@RequestBody LoginRequest loginRequest){
        Subject subject = null;
        try {
            subject = SecurityUtils.getSubject();
            subject.login(new UsernamePasswordToken(loginRequest.getUsername(),loginRequest.getPassword()));
            return  subject.getPrincipal();
        } catch (Exception e) {
            return e.getMessage();
        }
    }

    @PostMapping("/testRole")
    @RequiresRoles(value = {"dev","admin1"},logical = Logical.OR)
    public Object testRole(){
        return "success";
    }

    @PostMapping("/testOrRole")
    @RequiresRoles({"dev","123"})
    public Object testOrRole(){
        return "success";
    }

    @PostMapping("/testPerms")
    @RequiresPermissions({"user:delete"})
    public Object testPerms(){
        return "success";
    }

}
